//
//  StockAvailabilityViewController.m
//  EMMApp
//
//  Created by Mac on 16/7/10.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "StockAvailabilityViewController.h"
#import "EMMAnalysisCell.h"
#import "ZFChart.h"
#import "GetStockHouseListApi.h"
#import "GetDealHouseListApi.h"

@interface StockAvailabilityViewController ()<UITableViewDelegate,UITableViewDataSource> {
    NSString *timer;
    NSInteger cellHOne;
    NSInteger cellHTwo;

}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UILabel *djLabel;
@property (strong, nonatomic) ZFPieChart * pieChart;
@property (strong, nonatomic) ZFPieChart * pieChartTwo;

@property (strong, nonatomic) NSMutableArray *mjNameArr;
@property (strong, nonatomic) NSMutableArray *mjNumArr;

@property (strong, nonatomic) NSMutableArray *zjNameArr;
@property (strong, nonatomic) NSMutableArray *zjNumArr;

@property (strong, nonatomic) NSMutableArray *mjArr;
@property (strong, nonatomic) NSMutableArray *zjArr;


@end

@implementation StockAvailabilityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    cellHOne = 350;
    cellHTwo = 350;
    [self creatNavigationController];
    [self creatDropDownView];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, EMM_WIDTH, EMM_HEIGHT-SafeAreaTopHeight-40) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
  
    [_tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - 导航

- (void)creatNavigationController {
    [self updateNavBar];
    
    [self configLeftBtn];
    if (_isStock == YES) {
        self.navigationItem.title = @"存量房源分析";
    }else {
        self.navigationItem.title = @"成交房源分析";
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    _mjArr = [[NSMutableArray alloc] init];
    _zjArr = [[NSMutableArray alloc] init];
    _mjNameArr = [[NSMutableArray alloc] init];
    _mjNumArr = [[NSMutableArray alloc] init];
    _zjNameArr = [[NSMutableArray alloc] init];
    _zjNumArr = [[NSMutableArray alloc] init];

    timer = @"1";
    _djLabel.text = @"住宅";
    if (_isStock == YES) {//存量房源分析
        [self postGetStockHouseListApiHouseType:timer];
    }else {//成交房源分析
        [self postGetDealHouseListApiHouseType:timer];
    }
}


- (void)postGetStockHouseListApiHouseType:(NSString *)houseType {
    [self showHudInWindow:@"正在加载请稍等..."];
    [_mjArr removeAllObjects];
    [_zjArr removeAllObjects];
    [_mjNameArr removeAllObjects];
    [_mjNumArr removeAllObjects];
    [_zjNameArr removeAllObjects];
    [_zjNumArr removeAllObjects];
    GetStockHouseListApi *api = [[GetStockHouseListApi alloc] initWithHouseType:houseType];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetStockHouseListApi *result = (GetStockHouseListApi *)request;
        if (result.isSuccess) {
            GetStockHouseList *get = result.resultData;
            for (AreaSegmentList *list in get.areaSegmentList) {
                [_mjNameArr addObject:list.areaSegment];
                [_mjNumArr addObject:list.areaSegmentNum];
                [_mjArr addObject:list];
            }
            if (_mjArr.count > 0) {
                cellHOne = 350 +_mjArr.count * 25;
            }else {
                cellHOne = 350;
            }
            for (LumpSumList *list in get.lumpSumList) {
                [_zjNameArr addObject:list.lumpSum];
                [_zjNumArr addObject:list.lumpSumNum];
                [_zjArr addObject:list];

            }
            if (_zjArr.count > 0) {
                cellHTwo = 350 +_zjArr.count * 25;
            }else {
                cellHTwo = 350;
            }
            [self showPieChart];
            [self showPieChartvalue];
        } else {
            [self showToast:result.resultData.errorMsg];
            /*
             提示语：账号权限发生变动，请重新登录
             code随机18位唯一码：108E65843mYuwqb01X
             //YUplf0wyU5vPVssLSG 对应的异地登录退出登录
             */
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_tableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}

- (void)postGetDealHouseListApiHouseType:(NSString *)houseType {
    [self showHudInWindow:@"正在加载请稍等..."];

    [_mjArr removeAllObjects];
    [_zjArr removeAllObjects];
    [_mjNameArr removeAllObjects];
    [_mjNumArr removeAllObjects];
    [_zjNameArr removeAllObjects];
    [_zjNumArr removeAllObjects];
    
    GetDealHouseListApi *api = [[GetDealHouseListApi alloc] initWithHouseType:houseType];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        GetDealHouseListApi *result = (GetDealHouseListApi *)request;
        if (result.isSuccess) {
            GetDealHouseList *get = result.resultData;
            for (AreaSegmentList *list in get.areaSegmentList) {
                [_mjNameArr addObject:list.areaSegment];
                [_mjNumArr addObject:list.areaSegmentNum];
                [_mjArr addObject:list];
            }
            if (_mjArr.count > 0) {
                cellHOne = 350 +_mjArr.count * 25;
            }else {
                cellHOne = 350;
            }
            for (LumpSumList *list in get.lumpSumList) {
                [_zjNameArr addObject:list.lumpSum];
                [_zjNumArr addObject:list.lumpSumNum];
                [_zjArr addObject:list];
                
            }
            if (_zjArr.count > 0) {
                cellHTwo = 350 +_zjArr.count * 25;
            }else {
                cellHTwo = 350;
            }
            [self showPieChart];
            [self showPieChartvalue];
        } else {
            [self showToast:result.resultData.errorMsg];
            if ([result.resultData.errorCode isEqualToString:@"YUplf0wyU5vPVssLSG"] || [result.resultData.errorCode isEqualToString:@"108E65843mYuwqb01X"]) {
                NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
                NSDictionary *dictionary = [defs dictionaryRepresentation];
                for(NSString *key in [dictionary allKeys]){
                    if ([key isEqualToString:@"DeviceToken123"] ||
                        [key isEqualToString:@"loginText"] ||
                        [key isEqualToString:@"provinceCityDistrict"]) {
                    }else {
                        [defs removeObjectForKey:key];
                        [defs synchronize];
                    }
                }
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:result.resultData.errorMsg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    [appInstance showLogin];
                }];
                [alertController addAction:cancelAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
        [_tableView reloadData];
        [self hideHud];
    } failure:^(YTKBaseRequest *request) {
        [self showToast:@"连接服务器失败，请检查网络！"];
        [self hideHud];
    }];
}


#pragma mark - 跳出层初始化
- (void)creatDropDownView {//
    UIView *headBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, EMM_WIDTH, 40)];
    headBackView.backgroundColor = [UIColor colorFromHexCode:@"#fff5e9"];
    [self.view addSubview:headBackView];
    UIButton *djBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    djBtn.frame = CGRectMake(0, 0, EMM_WIDTH, 40);
    djBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [djBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [djBtn addTarget:self action:@selector(paheadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [headBackView addSubview:djBtn];
    UILabel *la1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 2, 20)];
    la1.backgroundColor = [UIColor whiteColor];
    [headBackView addSubview:la1];
    _djLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 20)];
    _djLabel.font = [UIFont systemFontOfSize:15];
    _djLabel.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
    [headBackView addSubview:_djLabel];
    
    UIImageView *im = [[UIImageView alloc] initWithFrame:CGRectMake(EMM_WIDTH-35, (40-15)/2, 25, 15)];
    im.image = [UIImage imageNamed:@"sanjt_down"];
    [headBackView addSubview:im];
}

- (void)paheadButtonClick:(UIButton *)btn {
    NSArray *arr = [NSArray arrayWithObjects:@"住宅",@"别墅",@"车位", nil];
    ShowMenuView *menuView = [[ShowMenuView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) title:@"选项" titleNmae:@"选择房产类型" numLits:nil items:arr];
    menuView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [[UIApplication sharedApplication].keyWindow addSubview:menuView];
    __block ShowMenuView *weakMenuView = menuView;//
    __block StockAvailabilityViewController *blockSelf = self;
    [menuView setTouchBlock:^(NSString *indet,NSString *number) {
        NSLog(@"%@",indet);
        if ([NSString isStringEmpty2:indet] == NO) {
            _djLabel.text = indet;
            timer = number;
            if (_isStock == YES) {//存量房源分析
                [blockSelf postGetStockHouseListApiHouseType:timer];
            }else {//成交房源分析
                [blockSelf postGetDealHouseListApiHouseType:timer];
            }
        }
        [weakMenuView removeFromSuperview];
    }];
}

#pragma mark - UITableView代理
//返回几个表头
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//每一个表头下返回几行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return cellHOne;
    }else {
        return cellHTwo;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"EMMAnalysisCellId";
    EMMAnalysisCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"EMMAnalysisCell" owner:self options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, cellHOne, EMM_WIDTH, 1)];
    imageView.backgroundColor = [UIColor colorFromHexCode:@"#bebebe"];
    if (indexPath.row == 0) {
        UILabel *la1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, EMM_WIDTH-20, 20)];
        la1.font = [UIFont systemFontOfSize:15];
        la1.text = @"按面积段";
        la1.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
        [cell addSubview:la1];
        [cell addSubview:imageView];
        if (_mjArr.count >0) {
            [cell addSubview:_pieChart];
        }else {
            UILabel *jlLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 300/2, EMM_WIDTH, 20)];
            jlLabel.text = @"当前没有记录";
            jlLabel.textAlignment = NSTextAlignmentCenter;
            jlLabel.font = [UIFont systemFontOfSize:15];
            jlLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
            [cell addSubview:jlLabel];
        }
    }else {
        UILabel *la1 = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, EMM_WIDTH-20, 20)];
        la1.font = [UIFont systemFontOfSize:15];
        la1.text = @"按总价段";
        la1.textColor = [UIColor colorFromHexCode:@"#5A5A5A"];
        [cell addSubview:la1];
        
        if (_zjArr.count >0) {
           [cell addSubview:_pieChartTwo];
        }else {
            UILabel *jlLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 300/2, EMM_WIDTH, 20)];
            jlLabel.text = @"当前没有记录";
            jlLabel.textAlignment = NSTextAlignmentCenter;
            jlLabel.font = [UIFont systemFontOfSize:15];
            jlLabel.textColor = [UIColor colorFromHexCode:@"#1A1A1A"];
            [cell addSubview:jlLabel];
        }
    }
    return cell;
}

- (void)showPieChartvalue{
    
   
    NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:
                            ZFColor(255, 231, 110, 1),ZFColor(255, 197, 153, 1),
                            ZFColor(255, 180, 103, 1),ZFColor(255, 144, 72, 1),
                            ZFColor(245, 74, 43, 1), ZFColor(251, 115, 136, 1),
                            ZFColor(245, 60, 127, 1),ZFColor(243, 53, 94, 1),
                            ZFColor(204, 31, 26, 1),ZFColor(117, 12, 12, 1),
                            ZFColor(197, 244, 255, 1),ZFColor(103, 194, 213, 1),
                            ZFColor(81, 153, 170, 1),ZFColor(4, 151, 150, 1),
                            ZFColor(8, 150, 104, 1),ZFColor(140, 211, 231, 1),
                            ZFColor(33, 185, 211, 1),ZFColor(0, 110, 168, 1),
                            ZFColor(0, 90, 166, 1),ZFColor(91, 84, 119, 1),nil];
    _pieChart = [[ZFPieChart alloc] initWithFrame:CGRectMake(0, 40, EMM_WIDTH, cellHOne) isInitWith:2];
    _pieChart.valueArray = _mjNumArr;
    _pieChart.nameArray = _mjNameArr;
    _pieChart.colorArray = arr3;
    _pieChart.percentType = kPercentTypeInteger;
    _pieChart.scrollEnabled = NO;
    [_pieChart strokePath:0];
}

- (void)showPieChart{
   
    NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:
                            ZFColor(255, 231, 110, 1),ZFColor(255, 197, 153, 1),
                            ZFColor(255, 180, 103, 1),ZFColor(255, 144, 72, 1),
                            ZFColor(245, 74, 43, 1), ZFColor(251, 115, 136, 1),
                            ZFColor(245, 60, 127, 1),ZFColor(243, 53, 94, 1),
                            ZFColor(204, 31, 26, 1),ZFColor(117, 12, 12, 1),
                            ZFColor(197, 244, 255, 1),ZFColor(103, 194, 213, 1),
                            ZFColor(81, 153, 170, 1),ZFColor(4, 151, 150, 1),
                            ZFColor(8, 150, 104, 1),ZFColor(140, 211, 231, 1),
                            ZFColor(33, 185, 211, 1),ZFColor(0, 110, 168, 1),
                            ZFColor(0, 90, 166, 1),ZFColor(91, 84, 119, 1),nil];
    _pieChartTwo = [[ZFPieChart alloc] initWithFrame:CGRectMake(0, 40, EMM_WIDTH, cellHTwo) isInitWith:2];
    _pieChartTwo.valueArray = _zjNumArr;
    _pieChartTwo.nameArray = _zjNameArr;
    _pieChartTwo.colorArray = arr3;
    _pieChartTwo.percentType = kPercentTypeInteger;
    _pieChartTwo.scrollEnabled = NO;
    [_pieChartTwo strokePath:0];
}


@end
